home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / math.swg / 0122_Prime Number funciton.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1997-03-05  |  1.6 KB  |  57 lines

  1. {           Prime v1.1 (C) 1997 Allen Cheng. All Rights Reserved.
  2.  
  3.    Please feel free to use this unit on your program,
  4.    give me Credit if you like.... Enjoy!
  5.  
  6.  This is quite fast, and is about 50-80% faster than the fastest one in SWAG.
  7.  As this Function is optimized for large numbers, you may not see any
  8.  differents is small numbers, but it only takes about 6 seconds to find all
  9.  the primes from 1000000 to 1020000. A newer version will be out soon
  10.  which should be about 10-20% faster.
  11.  
  12. Homepage:  http://www.geocities.com/SiliconValley/Park/8979/
  13. Email:     ac@4u.net
  14.  
  15. You can always download the newest version from my Homepage.
  16.  
  17. P.S. If you've found some ways to optimized this unit, please feel free to
  18. change anything, it's nice if you can send me a copy.
  19. }
  20. Unit Prime;
  21.  
  22. Interface
  23. Function PrimeChk(Num: LongInt): Boolean;
  24.  
  25. Implementation
  26.  
  27. Function PrimeChk(Num: LongInt): Boolean;
  28. Var x : Longint;
  29.     y : Integer;
  30. Begin
  31.  x := -1; y := 0;
  32.  Case Num Of
  33.   2,3 : Begin PrimeChk := True; Exit; End;
  34.   1 : Begin PrimeChk := False; Exit; End;
  35.  End;
  36. If (Num mod 2)=0 Then Begin PrimeChk := False; Exit; End; {Check if Even #}
  37.  
  38. While (Sqr(x) < Num) And (y < 2) Do
  39. Begin
  40.    x := x + 2; { Only check with Odd numbers }
  41.    If (Num mod x)=0 Then y:=y+1;
  42. End;
  43.  If y <> 1 Then PrimeChk := False Else PrimeChk := True;
  44. End;
  45.  
  46. End.
  47.  
  48. { ------------ DEMO --------------- }
  49.  
  50. Program Example;
  51. Uses Prime;
  52. Var Number : LongInt;
  53. Begin
  54. {List all Primes from 1000000 to 1020000}
  55. For Number := 1000000 to 1020000 Do
  56. If PrimeChk(Number) = True Then Write(Number,' ');
  57. End.